<template>
    <div class="page-controller">
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        :showCollapse="true"
        v-model:form-value="state.query"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="loginName" label="用户账号">
            <!-- <FIAutocomplete :dataArr="usersList" v-model="state.query.loginName">
              <template #default="{ item }">
                <div>{{ item.value }} {{ item.userName }}</div>
              </template>
            </FIAutocomplete> -->
            <FIInput v-model="state.query.loginName" clearable />
            <!-- <FIAutoSelect
              v-model="state.query.loginName"
              :props="{ value: 'loginName', label: 'loginName' }"
              :display-key="['loginName','userName']"
              api-url="/rm2/userMaint/query"
              searchParam="userAName"
            /> -->
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="logId" label="操作类型">
            <!-- <FIInput v-model="state.query.logId" clearable /> -->
            <FISelect
                v-model="state.query.logId"
                valueCustom="value"
                :options="dataArr"
                clearable
            />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="logContent" label="日志内容">
            <FIInput v-model="state.query.logContent" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="startTime" label="开始时间（到秒）">
            <FIDatePicker v-model="state.query.startTime" clearable type="datetime" value-format="YYYYMMDD"/>
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="endTime" label="结束时间（到秒）">
            <FIDatePicker v-model="state.query.endTime" clearable type="datetime" value-format="YYYYMMDD"/>
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="traceId" label="链路ID">
            <FIInput v-model="state.query.traceId" clearable />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="日志审计管理列表"
        :id="`result_${tableId}`"
        :readonly="false"
        :insertable="false"
        :data="state.dataList"
        :checkMode="'index'"
        primaryKey="token"
        v-model:columns="columns"
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="actionClick"
      >
        <template #headerBtn>
          <FIButton id="export" border class="margin-left5" @click="exportRow"></FIButton>
        </template>
      </FITable>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import FISelect from '@/components/FISelect/index.vue'
  
  import { apiRequestPost } from '@/api/globalApi.js'
  import LocalCache from '@/utils/cache'
  import { ElMessage } from 'element-plus'
  import { useMessage, useMessageBox } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import { apilogAudit, apilogExport, apiUserquery} from '@/api/user'
  import { apiGetCodeitems } from '@/api/configEnvMaint/index'
  import { getCurrentInstance } from 'vue'
  const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
  const route = useRoute()
  
  const searchWrapperSpan = 8
  const usersList = ref([])
  const dataArr = ref([])
  const showSearch = ref(true)
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'usersAudit'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const tableRef = ref(null)
  
  const state = reactive({
    query: {
      loginName: '',
      logId: '',
      logContent:'',
      startTime:'',
      endTime:'',
      traceId:'',
      current: 1,
      size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const columns: Column[] = reactive([
    {
      label: '链路ID',
      prop: 'traceId',
      align: 'center',
      editType: 'input',
      editable: true,
      sortable: false,
      // filterable: true,
      readonly: true,
  
      modelValue: {
        inputValue: '',
        isBlank: false,
        notBlank: false,
      },
    },
    {
      label: '用户账号',
      prop: 'x_ui',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '客户端IP',
      prop: 'x_ci',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '应用',
      prop: 'x_mn',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '类名',
      prop: 'u_cn',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '日志内容',
      prop: 'x_ii',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '业务数据',
      prop: 'u_dt',
      align: 'center',
      editType: 'input', 
    },
    {
      label: '时间',
      prop: 'x_st',
      align: 'center',
      editType: 'time', 
    },
    {
      label: '操作结果',
      prop: 'x_s',
      align: 'center',
      modelValue: { inputValue: '' },
      editType: 'select',
      editConfig: {
        options: [
          { value: '1', label: '成功' },
          { value: '0', label: '记录日志' },
          { value: '-1', label: '失败' },
        ],
      },
    },
    {
      label: '错误信息',
      prop: 'x_em',
      align: 'center',
      editType: 'input', 
    },
    {
        label: '操作类型',
        prop: 'x_li',
        align: 'center',
        width: '180',
        editable: true,
        editType: 'select',
        modelValue: [],
        editConfig: {
            options: dataArr,
            selectBinds: {
                multiple: false,
                valueCustom: 'value',
            },
        },
    },
  ])
  
  const checkedRows = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  const smallCode = () => {
    apiGetCodeitems({ codesetCode: 'iplat.ep.logType' })
        .then((res) => {
        if (res.data.success) {
            dataArr.value = res.data.data.map((v) => {
            return {
                label: v.itemCname,
                value: v.itemCode,
            }
            })
            tableRef.value.cloneColumnList.forEach((v) => {
            if (v.prop == 'x_li') {
                v.editConfig.options = dataArr
            }
            })
        }
        })
        .catch((error: any) => {})
    }
  //操作
  const actionClick = (item, rowData, btnInfo) => {
    useMessageBox()
      .confirm(`您确认要注销在线用户吗？`, '提示')
      .then(() => {
        if (item.type == 'delete') {
          const apiUrl = proxy.$Button_api('delete', route.name)
          apiRequestPost(apiUrl, { ...rowData })
            .then((res) => {
              if (res.data.success) {
                useMessage().success(res.data.message)
                searchFn()
              } else {
              }
            })
            .catch((error: any) => {})
        }
      })
      .catch(() => {})
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn('page')
  }
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
  
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    // const apiUrl = proxy.$Button_api('query', route.name)
    apilogAudit(state.query)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } 
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  
  const exportRow = () => {
    apilogExport(state.query)
  }
  const ruleFormRef = ref(null)
  
  const getUserList = () => {
    let par = {
      current: 1,
      size: 999,
    }
    apiUserquery(par)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          for (let i of res.data.data.result) {
            const obj = {
              value: i.loginName,
              userName: i.userName,
              userId: i.userId,
            }
            usersList.value.push(obj)
          }
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  onMounted(() => {
    smallCode()
    getUserList()
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
    searchFn()
  })
  </script>
  <style lang="less" scoped></style>
  